import React, { useEffect, useState } from 'react';
import { connect, useDispatch } from 'umi';
import {
  Input,
  Button,
  Divider,
  message,
  Modal,
  Table,
  Popconfirm,
  Row,
  Col,
  Form,
  Select,
  Alert,
  Typography,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import Ellipsis from '@/components/Ellipsis';
import PageTopFormContent from '@/components/PageTopFormContent';
import PaginationCommon from '@/components/PaginationCommon';
import OrgTreeSelect from '@/components/OrgTreeSelect';
import ResetPwdModal from '@/components/ResetPwdModal/ResetPwdModal';
import UserAddEdit from './components/UserAddEdit';
import styles from './UserManage.less';

const { confirm } = Modal;
const { Option } = Select;
const { Text } = Typography;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const UserManage = (props) => {
  const {
    userManageModel,
    common,
    loading: { effects },
  } = props;
  const { appCodeOfSelect } = common;
  const { userList, userListTotal } = userManageModel;
  const [currentPageNum, setCurrentPageNum] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [sort, setSort] = useState({ gmtCreated: 'desc' });
  const [formData, setFormData] = useState({});
  const [currentEditData, setCurrentEditData] = useState({});
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerType, setDrawerType] = useState('add');
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [userStateSearch, setUserStateSearch] = useState();
  const [allRoleList, setAllRoleList] = useState([]);
  const [resetPwdVisible, setResetPwdVisible] = useState(false);
  const [resetPwdUserData, setResetPwdUserData] = useState({});
  const isDeleteList = [
    {
      value: '',
      label: '全部'
    },
    {
      value: 'Y',
      label: '已删除'
    },
    {
      value: 'N',
      label: '未删除'
    }
  ];
  const dispatch = useDispatch();
  const [form] = Form.useForm();

  useEffect(() => {
    if (appCodeOfSelect) getAllRoleData();
  }, [appCodeOfSelect]);

  useEffect(() => {
    if (appCodeOfSelect) updateTableData();
  }, [currentPageNum, currentPageSize, formData, sort, userStateSearch, appCodeOfSelect]);

  const getAllRoleData = () => {
    dispatch({
      type: 'userManageModel/getAllRoleList',
      payload: { appCode: appCodeOfSelect },
    }).then((res) => {
      const { code, data } = res;
      if (code === 0) {
        setAllRoleList(data);
      }
    });
  };
  const updateTableData = () => {
    const currentData = {
      pageIndex: currentPageNum,
      pageSize: currentPageSize,
      userState: userStateSearch,
      appCode: appCodeOfSelect,
      ...formData,
    };

    if (sort) {
      currentData.sortMap = sort;
    }

    dispatch({
      type: 'userManageModel/getUserList',
      payload: currentData,
    });
  };

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values };
      setFormData(param);
      setCurrentPageNum(1);
      resetSelection();
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPageNum(1);
    setFormData({});
  };

  const handleShowEdit = (type, record) => {
    setDrawerType(type);
    setDrawerVisible(true);
    if (record) {
      setCurrentEditData(record);
    }
  };
  const handleCloseEdit = (updateFlag) => {
    setDrawerVisible(false);
    setCurrentEditData({});
    if (updateFlag === true) {
      handleSearch();
    }
  };

  const handleResetUserPwd = (record) => {
    setResetPwdUserData(record);
    setResetPwdVisible(true);
  };

  const handleCloseResetPwd = () => {
    setResetPwdUserData({});
    setResetPwdVisible(false);
  };

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPageNum(page);
    setCurrentPageSize(pageSize);
  };

  const handleTableChange = (_, filters, sorter) => {
    console.log(filters);
    const { userState } = filters;
    if (JSON.stringify(sorter) !== '{}') {
      const { field, order } = sorter;
      setSort({
        [field]: order === 'ascend' ? 'asc' : 'desc',
      });
    }
    if (userState && userState.length === 1) {
      setUserStateSearch(userState[0]);
    } else {
      setUserStateSearch('');
    }
  };

  const handleChangeUserState = (idsList, action) => {
    dispatch({
      type: `userManageModel/${action === 'activate' ? 'activateUser' : 'freezeUser'}`,
      payload: idsList,
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0) {
        message.success(`${action === 'activate' ? '激活' : '冻结'}成功`);
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };

  const handleBatchOpt = (optText) => {
    if (selectedRowKeys.length === 0) {
      message.warn(`请勾选要${optText}的用户`);
      return false;
    }
    const userNameList = [];
    const userIdList = [];
    selectedRows.forEach((item) => {
      userNameList.push(item.userName);
      userIdList.push(item.id);
    });
    confirm({
      title: `确定要批量${optText}：${
        userNameList.length > 3
          ? `${userNameList.slice(0, 3).join('、')}等`
          : userNameList.join('、')
      }用户吗？`,
      onOk() {
        if (optText === '删除') {
          handleDel(userIdList);
        } else {
          handleChangeUserState(userIdList, optText === '激活' ? 'activate' : 'freeze');
        }
      },
    });
  };

  // 复效用户
  const handleRecovery = (idList) => {
    dispatch({
      type: 'userManageModel/revalidateSysUser',
      payload: idList,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('复效成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  }

  // 删除用户
  const handleDel = (idList) => {
    dispatch({
      type: 'userManageModel/deleteUser',
      payload: idList,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('删除成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeysParam, selectedRowsParam) => {
      setSelectedRowKeys(selectedRowKeysParam);
      setSelectedRows(selectedRowsParam);
    },
  };

  const resetSelection = () => {
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  const columns = [
    {
      title: '用户 ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户账号',
      dataIndex: 'userAccount',
      key: 'userAccount',
    },
    {
      title: '工号',
      dataIndex: 'employeeCode',
      key: 'employeeCode',
    },
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '组织',
      dataIndex: 'orgs',
      key: 'orgs',
      render: (val) =>
        val ? (
          <Text style={{ width: 120 }} ellipsis={{ tooltip: val }}>
            {val}
          </Text>
        ) : (
          '-'
        ),
      // render: (text) =>
      //   text ? (
      //     <Ellipsis length={40} tooltip fullWidthRecognition>
      //       {text}
      //     </Ellipsis>
      //   ) : (
      //     ''
      //   ),
    },
    {
      title: '角色',
      dataIndex: 'roleList',
      key: 'roleList',
      ellipsis: {
        showTitle: false,
      },
      render: (roleList) => {
        const text = roleList?.map((item) => item.roleName).join('、') || '-';
        return (
          <Text style={{ width: 120 }} ellipsis={{ tooltip: text }}>
            {text}
          </Text>
        );
      },
      // render: (roleList) =>
      //   roleList && roleList.length > 0 ? (
      //     <Ellipsis length={40} tooltip fullWidthRecognition>
      //       {roleList.map((item) => item.roleName).join(',')}
      //     </Ellipsis>
      //   ) : (
      //     ''
      //   ),
    },
    {
      title: '是否删除',
      dataIndex: 'isDeleted',
      key: 'isDeleted',
      render: (text) => (
        <span>{text === 'Y' ? '已删除' : '未删除'}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'userState',
      key: 'userState',
      filters: [
        { text: '激活', value: 1 },
        { text: '未激活', value: 0 },
      ],
      render: (text) => (
        <span style={{ color: `${text === 1 ? '#1E8E3E' : '#999999'}` }}>
          ●{text === 0 ? '未激活' : '激活'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      sorter: true,
      defaultSortOrder: 'descend',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      fixed: 'right',
      render: (record) => (
        <div>
          {record.userState === 1 ? (
            record.isDeleted === 'N' ?
            <Popconfirm
              title="确定要冻结该用户吗？"
              onConfirm={() => handleChangeUserState([record.id], 'freeze')}
            >
              <Button type="link">冻结</Button>
            </Popconfirm> :
            <Button type="link" disabled>冻结</Button>
          ) : (
            record.isDeleted === 'N' ?
            <Popconfirm
              title="确定要激活该用户吗？"
              onConfirm={() => handleChangeUserState([record.id], 'activate')}
            >
              <Button type="link">激活</Button>
            </Popconfirm> :
            <Button type="link" disabled>激活</Button>
          )}
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleResetUserPwd(record)} disabled={record.isDeleted === 'Y'}>
            重置密码
          </Button>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowEdit('edit', record)} disabled={record.isDeleted === 'Y'}>
            修改
          </Button>
          <Divider type="vertical" />
          {record.isDeleted === 'Y' ? (
            <Popconfirm
              title="确定要复效该用户吗？"
              onConfirm={() => handleRecovery([record.id])}
            >
              <Button type="link">复效</Button>
            </Popconfirm>
          ) : (
            <Popconfirm title="确定要删除该用户吗？" onConfirm={() => handleDel([record.id])}>
              <Button type="link">删除</Button>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className={styles.root}>
      <PageTopFormContent
        title="用户管理"
        content={
          <Form {...layout} form={form}>
            <Row gutter={[32, 16]}>
              <Col span={6}>
                <Form.Item name="userId" label="用户ID">
                  <Input placeholder="请输入用户ID" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="userAccount" label="用户账号">
                  <Input placeholder="请输入用户账号" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="employeeCode" label="工号">
                  <Input placeholder="请输入工号" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="orgIdList" label="组织">
                  <OrgTreeSelect
                    dropdownMatchSelectWidth={false}
                    dropdownStyle={{ maxWidth: 400 }}
                    treeCheckable
                    placeholder="请选择组织"
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="userName" label="姓名">
                  <Input placeholder="请输入姓名" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="roleIdList" label="角色">
                  <Select mode="multiple" placeholder="请选择角色">
                    {allRoleList.map((item) => (
                      <Option key={item.roleId} value={item.roleId}>
                        {item.roleName}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="isDeleted" label="是否删除">
                  <Select placeholder="请选择">
                    {isDeleteList.map((item, index) => (
                      <Option key={index} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6} style={{ textAlign: 'right' }}>
                <Form.Item wrapperCol={{ span: 24 }}>
                  <Button type="primary" onClick={handleSearch}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      />
      <div className={styles.bottomWrapper}>
        <div className={styles.rightTable}>
          <div className={styles.rightTableTop}>
            <div className={styles.left}>
              <div className={styles.title}>用户列表</div>
            </div>
            <div className={styles.right}>
              {selectedRowKeys.length !== 0 && (
                <Alert
                  type="info"
                  message={
                    <>
                      已选中 <strong>{selectedRowKeys.length}</strong> 条数据
                      <Button
                        type="link"
                        size="small"
                        onClick={() => {
                          resetSelection();
                        }}
                      >
                        清空
                      </Button>
                    </>
                  }
                  style={{ display: 'inline-block', padding: '3px 6px' }}
                />
              )}
              <Button onClick={() => handleBatchOpt('激活')}>批量激活</Button>
              <Button onClick={() => handleBatchOpt('冻结')}>批量冻结</Button>
              <Button
                onClick={() => handleBatchOpt('删除')}
                type="danger"
                disabled={selectedRows.length === 0}
              >
                批量删除
              </Button>
              <Button type="primary" onClick={() => handleShowEdit('add')}>
                <PlusOutlined />
                添加用户
              </Button>
            </div>
          </div>
          <div className={styles.tableWrapper}>
            <Table
              rowKey="id"
              loading={effects['userManageModel/getUserList']}
              rowSelection={{
                ...rowSelection,
              }}
              columns={columns}
              dataSource={userList}
              pagination={false}
              scroll={{ x: 'max-content' }}
              onChange={handleTableChange}
            />
            <PaginationCommon
              total={userListTotal}
              onChange={handlePaginationChange}
              style={{ textAlign: 'right' }}
              current={currentPageNum}
              pageSize={currentPageSize}
            />
          </div>
        </div>
      </div>
      {drawerVisible && (
        <UserAddEdit
          editData={currentEditData}
          allRoleList={allRoleList}
          drawerType={drawerType}
          handleClose={handleCloseEdit}
          appCode={appCodeOfSelect}
        />
      )}
      {resetPwdVisible && (
        <ResetPwdModal userData={resetPwdUserData} handleClose={handleCloseResetPwd} />
      )}
    </div>
  );
};

export default connect((state) => state)(UserManage);
